package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper mapper;


    public void delete(Long id) {

        //先删除关系
        mapper.deleteRelation(id);

        mapper.deleteByPrimaryKey(id);
    }

    public void save(Employee entity) {

        entity.setInputTime(new Date());
        entity.setState(Employee.STATE_NORMAL);
        entity.setAdmin(false);

        mapper.insert(entity);

        //维护与角色的关系
        List<Role> roles = entity.getRoles();
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                mapper.saveRelation(entity.getId(), role.getId());
            }
        }

    }
    public void update(Employee entity) {

        //先删除关系,然后再维护关系
        mapper.deleteRelation(entity.getId());

        mapper.updateByPrimaryKey(entity);

        //维护与角色的关系
        List<Role> roles = entity.getRoles();
        if (roles != null&& roles.size() > 0) {
            for (Role role : roles) {
                mapper.saveRelation(entity.getId(), role.getId());
            }
        }
    }

    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Employee> list() {
        return mapper.selectAll();
    }

    //高级查询
    public PageResult query(EmployeeQueryObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Employee> list = mapper.queryForList(qo);
        return new PageResult(total,list);
    }

    //离职与复职
    public void changeState(Long id) {
        mapper.changeState(id);
    }

    public Employee getEmployeeByUsername(String username) {
        return mapper.getEmployeeByUsername(username);
    }

    public List<Employee> listData() {
        return mapper.listData();
    }
}
